#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import datetime
import backtrader as bt
import backtrader.feeds as btfeeds

def date2str(date, _format_str="%Y-%m-%d %H:%M:%S"):
    return date.strftime(_format_str)

class St1(bt.Strategy):

    def __init__(self):
        pass

    def next(self):
        dt0 = date2str(self.data0.datetime.datetime())
        dt1 = date2str(self.data1.datetime.datetime())
        print("dt0--: %s, %.2f, %.2f, %.2f, %.2f, %.2f" % (
        dt0, self.data0.open[0], self.data0.high[0], self.data0.low[0], self.data0.close[0], self.data0.volume[0]))
        print("dt1++: %s, %.2f, %.2f, %.2f, %.2f, %.2f" % (
        dt1, self.data1.open[0], self.data1.high[0], self.data1.low[0], self.data1.close[0], self.data1.volume[0]))


def runstrat():
    args = parse_args()

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(St1)

    # Load the Data
    datapath = args.dataname or '/Users/wudi/Downloads/BTC_USDT.csv'
    fromdate = datetime.datetime.strptime("2021-08-01", '%Y-%m-%d')
    todate = datetime.datetime.strptime("2021-08-02", '%Y-%m-%d')
    data = btfeeds.GenericCSVData(
        dataname=datapath,
        dtformat='%Y-%m-%d %H:%M:%S',
        fromdate=fromdate,
        todate=todate,
        timeframe=bt.TimeFrame.Minutes,
        # sessionstart=datetime.time(0, 0, 0),
        # sessionend=datetime.time(23, 59, 59),
        compression=15
    )

    # Handy dictionary for the argument timeframe conversion


    cerebro.adddata(data)
    # Resample the data
    cerebro.resampledata(
        data,
        timeframe=bt.TimeFrame.Minutes,
        compression=60,
        boundoff=15,
        adjbartime=True,
        rightedge=True,
        bar2edge=True)

    if args.writer:
        # add a writer
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)

    # Run over everything
    cerebro.run()

    # Plot the result
    # cerebro.plot(style='bar')


def parse_args():
    parser = argparse.ArgumentParser(
        description='Resampling script down to tick data')

    parser.add_argument('--dataname', default='', required=False,
                        help='File Data to Load')

    parser.add_argument('--timeframe', default='minutes', required=False,
                        choices=['ticks', 'microseconds', 'seconds',
                                 'minutes', 'daily', 'weekly', 'monthly'],
                        help='Timeframe to resample to')

    parser.add_argument('--compression', default=1, required=False, type=int,
                        help=('Compress n bars into 1'))

    parser.add_argument('--nobar2edge', required=False, action='store_true',
                        help=('Do not Resample IntraDay Timed Bars to edges'))

    parser.add_argument('--noadjbartime', required=False,
                        action='store_true',
                        help=('Do not adjust the time bar to meet the edges'))

    parser.add_argument('--rightedge', required=False, action='store_true',
                        help=('Resample to right edge of boundary'))

    parser.add_argument('--writer', required=False, action='store_true',
                        help=('Add a Writer'))

    parser.add_argument('--wrcsv', required=False, action='store_true',
                        help=('Add CSV to the Writer'))

    return parser.parse_args()


if __name__ == '__main__':
    runstrat()
